/* eslint-disable max-len */
import React from 'react';
import { DatePicker, Form, List, Modal, Image, notification as Notification } from 'antd';
import moment from 'moment';
import './BookDetail.scss';
import { borrowBook, getBookInfoById } from '../../../api/bookInfo';

const { RangePicker } = DatePicker;
const dateFormat = 'yyyy-MM-DD HH:mm:ss';

class BookDetail extends React.Component {
  state = {
    expectedReturnTime: '',
    visible: false,
    bookInfoId: 0,
    bookInfo: {},
  };

  constructor(props) {
    super(props);
    const { match } = props;
    const bookInfoId = match.params.id;

    this.state = {
      expectedReturnTime: moment().add(15, 'days').format(dateFormat),
      visible: false,
      bookInfoId,
      bookInfo: {},
      listData: [],
    };
    this.getBookInfo();
  }

  componentDidMount() {
    let format = 'yyyy-MM-DD HH:mm:ss';
    let s = moment().format(format);
    console.log(s, typeof s, 's');
    s = moment('2015/01/01', format);
    console.log(s, typeof s, 's');
    s = moment().add(45, 'days');
    console.log(s, typeof s, 's');
  }

  getBookInfo=() => {
    const { bookInfoId } = this.state;
    getBookInfoById(bookInfoId).then(({ data: bookInfo }) => {
      this.setState({
        bookInfo
      });
    }).catch((e) => {
      console.log(e, typeof e, 'getUserById e');
    });
  };

  borrowBook = () => {
    const { expectedReturnTime, bookInfoId: id } = this.state;

    borrowBook({ expectedReturnTime, id }).then(({ data }) => {
      console.log(data, typeof data, 'data');
      Notification.success({
        message: `借阅 ${data.name} 成功`,
        duration: 2
      });
      this.setState({ visible: false });
      this.getBookInfo();
    }).catch((e) => {
      console.log(e, typeof e, 'listBookInfo e');
    });
    console.log('borrowBook', typeof 'borrowBook', 'borrowBook');
  };

  render() {
    const { bookInfo, visible } = this.state;

    const data = [
      { label: '书籍名称', value: bookInfo.name },
      { label: 'ISBN', value: bookInfo.isbn },
      { label: '作者', value: bookInfo.author },
      { label: '出版社', value: bookInfo.publisher },
      { label: '字数', value: bookInfo.words },
      { label: '分类', value: bookInfo.classificationName },
      { label: '分享者', value: bookInfo.ownerUserName },
      {
        label: '图书状态',
        value: (<span className={'borrowed-state ' + (bookInfo.borrowed ? 'borrowed' : '')}>
          {bookInfo.borrowed ? '已借阅出'
            : (<a onClick={() => {
              this.setState({ visible: true });
            }}>可借阅</a>)}
        </span>)
      },
      { label: '分享时间', value: bookInfo.createTime },
      { label: '作者', value: bookInfo.author },
    ];

    /*
        author: "磨铁出品； 当年明月 著"
        borrowUserId: null
        borrowUserName: null
        borrowed: false
        borrowedTime: null
        classificationId: 853
        classificationName: "中国史"
        coverImage: "144096255654494208.jpg"
        createBy: "admin"
        createTime: "2020-11-01 15:07:04"
        desc: "《明朝那些事儿》主要讲述的是从1344年到1644年这三百年间关于明朝的一些事情，以史料为基础，以年代和具体人物为主线，并加入了小说的笔法，对明朝十七帝和其他王公权贵和小人物的命运进行全景展示，尤其对官场政治、战争、帝王心术着墨ZUI多，并加入对当时政治经济制度、人伦道德的演义。"
        expectedReturnTime: null
        id: 23
        isbn: "9787559602152"
        name: "明朝那些事儿（全套共9册增补版）"
        ownerUserId: 1
        ownerUserName: "小白"
        publisher: "北京联合出版公司"
        remark: null
        updateBy: "admin"
        updateTime: "2020-11-01 15:07:04"
        words: "52000"
        */
    const renderItem = (item) => (<List.Item className="book-info-item">
      <span className="label">{item.label}:</span>
      <span className="value">{item.value}</span>
    </List.Item>);

    const onDateChange = (date) => {
      const [start, end] = date;
      console.log([start, end], typeof [start, end], '[start, end]');
      this.setState({
        expectedReturnTime: end.format(dateFormat)
      });
    };
    return (
      <div className="book-detail-container">
        <h1>书籍详细信息:</h1>
        <div className="book-detail">
          <Image
            height={500}
            src={bookInfo.coverImage ? 'http://localhost:8077/bookSharing/common/image?fileName=' + bookInfo.coverImage : ''}
          />
          <div className="book-info">
            <List
              dataSource={data}
              renderItem={renderItem}
            />
          </div>
        </div>
        <div className="content-warp">
          <pre className="content">{bookInfo.desc}</pre>
        </div>
        <Modal
          visible={visible}
          destroyOnClose
          title="预计归还时间"
          okText="确定"
          cancelText="取消"
          onCancel={() => {
            this.setState({ visible: false });
          }}
          onOk={this.borrowBook}
          maskClosable={false}
        >
          <Form
            ref={this.formRef}
            {
              ...{
                labelCol: { span: 4 },
                wrapperCol: { span: 20 },
              }
            }
            name="userForm"
          >
            <RangePicker
              showTime
              format={dateFormat}
              disabledDate={(current) => current.diff(moment(), 'days') > 45}
              defaultValue={[moment(), moment().add(15, 'days')]}
              disabled={[true, false]}
              onOk={onDateChange}
            />
          </Form>
        </Modal>
      </div>
    );
  }
}

export default BookDetail;
